<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="索引支持在 MongoDB 中高效执行查询。 如果没有索引，MongoDB 必须执行集合扫描，即扫描集合中的每个文档，以选择那些与查询语句匹配的文档。如果查询存在合适的索引，MongoDB 可以使用该索引来限制它必须检查的文档数量。 索引是特殊的数据结构（MongoDB 索引使用 B 树数据结构），它以易于遍历的形式存储集合数据集的一小部分。索引存储特定字段或字段集的值，按字段值排序。索引条目的排">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB 索引">
<meta property="og:url" content="http://example.com/2021/11/02/MongoDB%20%E7%B4%A2%E5%BC%95/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="索引支持在 MongoDB 中高效执行查询。 如果没有索引，MongoDB 必须执行集合扫描，即扫描集合中的每个文档，以选择那些与查询语句匹配的文档。如果查询存在合适的索引，MongoDB 可以使用该索引来限制它必须检查的文档数量。 索引是特殊的数据结构（MongoDB 索引使用 B 树数据结构），它以易于遍历的形式存储集合数据集的一小部分。索引存储特定字段或字段集的值，按字段值排序。索引条目的排">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://docs.mongodb.com/manual/images/index-ascending.bakedsvg.svg">
<meta property="og:image" content="https://docs.mongodb.com/manual/images/index-compound-key.bakedsvg.svg">
<meta property="og:image" content="https://docs.mongodb.com/manual/images/index-multikey.bakedsvg.svg">
<meta property="article:published_time" content="2021-11-02T00:08:21.000Z">
<meta property="article:modified_time" content="2021-11-02T00:41:33.247Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="NoSQL">
<meta property="article:tag" content="MongoDB">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://docs.mongodb.com/manual/images/index-ascending.bakedsvg.svg">


<link rel="canonical" href="http://example.com/2021/11/02/MongoDB%20%E7%B4%A2%E5%BC%95/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/11/02/MongoDB%20%E7%B4%A2%E5%BC%95/","path":"2021/11/02/MongoDB 索引/","title":"MongoDB 索引"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>MongoDB 索引 | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%BB%98%E8%AE%A4-id%E7%B4%A2%E5%BC%95"><span class="nav-number">1.</span> <span class="nav-text">默认_id索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA%E7%B4%A2%E5%BC%95"><span class="nav-number">2.</span> <span class="nav-text">创建索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9F%A5%E7%9C%8B%E7%B4%A2%E5%BC%95"><span class="nav-number">3.</span> <span class="nav-text">查看索引</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%B4%A2%E5%BC%95%E7%B1%BB%E5%9E%8B"><span class="nav-number">4.</span> <span class="nav-text">索引类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8D%95%E5%AD%97%E6%AE%B5%E7%B4%A2%E5%BC%95"><span class="nav-number">4.1.</span> <span class="nav-text">单字段索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%8D%E5%90%88%E7%B4%A2%E5%BC%95"><span class="nav-number">4.2.</span> <span class="nav-text">复合索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%9A%E9%94%AE%E7%B4%A2%E5%BC%95"><span class="nav-number">4.3.</span> <span class="nav-text">多键索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%93%88%E5%B8%8C%E7%B4%A2%E5%BC%95"><span class="nav-number">4.4.</span> <span class="nav-text">哈希索引</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/02/MongoDB%20%E7%B4%A2%E5%BC%95/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="MongoDB 索引 | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MongoDB 索引
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-11-02 08:08:21 / 修改时间：08:41:33" itemprop="dateCreated datePublished" datetime="2021-11-02T08:08:21+08:00">2021-11-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/NoSQL/" itemprop="url" rel="index"><span itemprop="name">NoSQL</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <p>索引支持在 MongoDB 中高效执行查询。</p>
<p><strong>如果没有索引，MongoDB 必须执行<em>集合扫描</em>，即扫描<em>集合中的</em>每个文档，以选择那些与查询语句匹配的文档</strong>。如果查询存在合适的索引，MongoDB 可以使用该索引来限制它必须检查的文档数量。</p>
<p>索引是特殊的数据结构（<strong>MongoDB 索引使用 B 树数据结构</strong>），它以易于遍历的形式存储集合数据集的一小部分。索引存储特定字段或字段集的值，按字段值排序。索引条目的排序支持高效的等式匹配和基于范围的查询操作。此外，MongoDB 可以使用索引中的排序返回排序结果。</p>
<p>从根本上说，<strong>MongoDB 中的索引类似于其他数据库系统中的索引</strong>（因为数据结构使用的都是B树）。MongoDB 在<strong>集合</strong>级别定义索引，并支持 MongoDB 集合中文档的任何字段或子字段的索引。</p>
<h2 id="默认-id索引"><a href="#默认-id索引" class="headerlink" title="默认_id索引"></a>默认<code>_id</code>索引</h2><p>MongoDB在创建集合期间在<code>_id</code>字段上 创建唯一索引。该索引可防止客户端插入具有相同字段值的两个文档。您不能在字段上删除此索引。</p>
<h2 id="创建索引"><a href="#创建索引" class="headerlink" title="创建索引"></a>创建索引</h2><p>索引一旦创建就不能重命名。相反，您必须删除并使用新名称重新创建索引。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.createIndex( &lt;key and index type specification&gt;, &lt;options&gt; )</span><br></pre></td></tr></table></figure>

<h2 id="查看索引"><a href="#查看索引" class="headerlink" title="查看索引"></a>查看索引</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.getIndexes()</span><br></pre></td></tr></table></figure>




<h2 id="索引类型"><a href="#索引类型" class="headerlink" title="索引类型"></a>索引类型</h2><p>MongoDB 提供了许多不同的索引类型来支持特定类型的数据和查询。</p>
<h3 id="单字段索引"><a href="#单字段索引" class="headerlink" title="单字段索引"></a>单字段索引</h3><p>MongoDB支持在文档的单个字段上创建用户定义的升序&#x2F;降序索引。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.createIndex( &#123; score: 1 &#125; )</span><br></pre></td></tr></table></figure>



<p><img src="https://docs.mongodb.com/manual/images/index-ascending.bakedsvg.svg"></p>
<h3 id="复合索引"><a href="#复合索引" class="headerlink" title="复合索引"></a>复合索引</h3><p>MongoDB 还支持多个字段上的用户定义索引，即 <a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/core/index-compound/">复合索引</a>。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.collection.createIndex( &#123; userid: 1, score: -1 &#125; )</span><br></pre></td></tr></table></figure>



<p>复合索引中列出的字段顺序很重要。例如，如果复合索引由 组成<code>&#123; userid: 1, score: -1 &#125;</code>，则索引首先按升序排序<code>userid</code>，然后在每个<code>userid</code> 值中按降序排序<code>score</code>。</p>
<p><img src="https://docs.mongodb.com/manual/images/index-compound-key.bakedsvg.svg"></p>
<h3 id="多键索引"><a href="#多键索引" class="headerlink" title="多键索引"></a>多键索引</h3><p>MongoDB 使用<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/core/index-multikey/">多键索引</a>来索引<strong>存储在数组中的内容</strong>。<br>如果你索引一个包含数组值的字段，MongoDB 会<strong>为数组的每个元素创建单独的索引条目</strong>。这些<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/core/index-multikey/">多键索引</a>允许查询通过匹配数组的一个或多个元素来选择包含数组的文档。</p>
<p>如果索引字段包含数组值，MongoDB 会自动判断是否创建多键索引；您<strong>不需要显式指定多键类型</strong>。</p>
<p><img src="https://docs.mongodb.com/manual/images/index-multikey.bakedsvg.svg"></p>
<h3 id="哈希索引"><a href="#哈希索引" class="headerlink" title="哈希索引"></a>哈希索引</h3><p>为了支持<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/core/hashed-sharding/#std-label-sharding-hashed-sharding">基于散列的分片</a>，MongoDB 提供了一种<a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/core/index-hashed/">散列索引</a>类型，它对字段值的散列值进行索引。这些索引在其范围内具有更随机的值分布，但<strong>仅支持相等匹配</strong>，<strong>不支持基于范围的查询</strong>。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://docs.mongodb.com/manual/indexes/">官方文档索引</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/NoSQL/" rel="tag"># NoSQL</a>
              <a href="/tags/MongoDB/" rel="tag"># MongoDB</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/10/31/MySQL%E7%B3%BB%E5%88%97%E2%80%94%E2%80%94-InnoDB%E7%9A%84MVCC%E6%9C%BA%E5%88%B6/" rel="prev" title="MySQL系列—— InnoDB的MVCC机制">
                  <i class="fa fa-chevron-left"></i> MySQL系列—— InnoDB的MVCC机制
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/11/02/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E5%90%84%E7%A7%8D%E9%81%8D%E5%8E%86%EF%BC%88%E9%80%92%E5%BD%92%E4%B8%8E%E8%BF%AD%E4%BB%A3%E5%AE%9E%E7%8E%B0%EF%BC%89%E4%BB%A5%E5%8F%8A%E4%BD%BF%E7%94%A8%E4%B8%AD%E5%BA%8F%E3%80%81%EF%BC%88%E5%89%8D%E5%BA%8F-%E5%90%8E%E5%BA%8F%EF%BC%89%E8%BF%98%E5%8E%9F%E4%BA%8C%E5%8F%89%E6%A0%91/" rel="next" title="二叉树的各种遍历（递归与迭代实现）以及使用中序、（前序 | 后序）还原二叉树">
                  二叉树的各种遍历（递归与迭代实现）以及使用中序、（前序 | 后序）还原二叉树 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
